from time import sleep
import shutil
import psutil
import os
import filecmp
import sys


def check(a):
    if not os.path.isdir(a):
        print("路径不是文件夹！" + a)
        return False
    # elif not os.path.abspath(a) == a:
    #     print("路径不是绝对路径！" + a)
    #     return False
    else:
        return True


def autobackup(scrdir, dstdir):
    if not (check(scrdir) and check(dstdir)):
        print("err 001")
        sys.exit(0)
    # if os.listdir(scrdir) != []:
    #     os.listdir(scrdir).pop(0)
    for i in os.listdir(scrdir):

        scri = os.path.join(scrdir, i)
        #dsti = scri.replace(scrdir, dstdir)
        dsti = os.path.join(dstdir, i)
        if os.path.isdir(scri):
            if not os.path.exists(dsti):
                os.mkdir(dsti)
                print("创建文件夹："+dsti)
            autobackup(scri, dsti)
        elif os.path.isfile(scri):
            if (not os.path.exists(dsti)) or (not filecmp.cmp(scri, dsti, shallow=False)):
                shutil.copyfile(scri, dsti)
                print("文件复制："+dsti)


def his(scrdir, dstdir, hisdir):

    # if os.listdir(dstdir) != []:
    #     os.listdir(dstdir).pop(0)
    for j in os.listdir(dstdir):
        dsti = os.path.join(dstdir, j)
        scri = os.path.join(scrdir, j)
        hisi = os.path.join(hisdir, j)
        if os.path.isdir(dsti):
            if not os.path.exists(scri):
                os.mkdir(hisi)
                os.rmdir(dsti)
                #shutil.move(dsti, hisi)
                print("转移文件夹：" + dsti)
            his(scri, dsti, hisi)
        elif os.path.isfile(dsti):
            if not os.path.exists(scri):
                shutil.move(dsti, hisi)
                print("转移文件：" + hisi)


while True:
    sleep(1)
    isfind = False
    now = r'E:\Udisk\now'
    history = r'E:\Udisk\history'
    for i in psutil.disk_partitions():
        if 'removable' in i.opts:
            driver, opts = i.device, i.opts
            print('find usb driver:', driver)
            # print(now, history)
            autobackup(driver, now)
            if not (check(driver) and check(now) and check(history)):
                print("his check err!")
                sys.exit(0)
            his(driver, now, history)
            isfind = True
            break
        else:
            print('can\'t find usb driver')
            continue
    #break
    if isfind:
        break

